//
//  MGMainViewController.swift
//  微博
//
//  Created by 陈明光 on 2019/11/5.
//  Copyright © 2019 陈明光. All rights reserved.
//

import UIKit
//主控制器
class MGMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

       setupChildControllers()
       setupComposeButton()
    }
    
//    func supportedInterfaceOrientations() -> UIInterfaceOrientationMask{
//        return .portrait
//    }
    
    //MARK: - 撰写按钮监听方法
    //private:能够保证方法私有，仅在当前对象被访问
    //@objc 允许这个函数运行时通过 OC 的消息机制被调用
     @objc private func composeStatus(){
        print("撰写微博")
        
        //测试方向旋转
        let vc = UIViewController()
        
        vc.view.backgroundColor = UIColor.cz_random()
        let nav = UINavigationController(rootViewController: vc)
        
        
        present(nav, animated: true,completion: nil)
        
    }
    
    //MARK: - 私有控件
    //backgroundImageName:背景图片
    private lazy var composeButton: UIButton = UIButton.cz_imageButton(
        "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
}
//extension 类似于OC 中的分类 ，在Swift 中，还可以用来切分代码块
//可以把相近功能的函数，放在一个extension 中
//便于代码维护
//注意：和OC的分类一样 extension不能定义属性
//MARK: - 设置界面
extension MGMainViewController{
    
    //设置撰写按钮
    private func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        //计算按钮的宽度
        let count = CGFloat(children.count)
        let w = tabBar.bounds.width / count - 1
        //让撰写按钮水平的往里面缩两个子控件
        //正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    //设置所有子控制器
    private func setupChildControllers(){
        
        //0.获取沙盒json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        //判断data是否有内容，如果没有，说明本地沙盒没有文件
        if data == nil {
            //从Bundle(本地) 加载data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
        }
        
        //data一定会有一个内容，反序列化 throw 抛出异常
        //方法一：推荐try？，如果解析成功，就有值，否则为nil
        //1.路径/2.加载NSData / 3.反序列化转化成数组
        guard let array = try? JSONSerialization.jsonObject(with: data!as Data, options: []) as? [[String: AnyObject]]
            else{
            return
        }
       
        
//        //现在的很多应用程序中，界面的创建都依赖网络的json
//        let array:[[String: AnyObject]] = [
//            ["clsName":"MGHomeViewController" as AnyObject,"title":"首页" as AnyObject,"imagName":"home" as AnyObject,
//                      "visitorInfo": ["imageName": "", "message": "关注一些人，回这里看看有什么惊喜"] as AnyObject
//                    ],
//
//            ["clsName":"MGMessageViewController" as AnyObject,"title":"消息" as AnyObject,"imagName":"message_center" as AnyObject,
//             "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登陆后，别人评论你的微博，发给你的消息，都会在这里收到通知"] as AnyObject],
//
//            ["clsName":"UIViewControlle" as AnyObject],
//
//            ["clsName":"MGDiscoverViewController" as AnyObject,"title":"发现" as AnyObject,"imagName":"discover" as AnyObject,
//             "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登陆后，最新，最热微博尽在掌握，不再会与实事潮流擦肩而过"] as AnyObject],
//
//            ["clsName":"MGProfileViewController" as AnyObject,"title":"我" as AnyObject,"imagName":"profile" as AnyObject,
//             "visitorInfo": ["imageName": "visitordiscover_image_profile", "message": "登陆后，你的微博、相册、个人资料会显示在这里，展示给别人"] as AnyObject
//            ],
//            ]
//        //测试数据格式是否正确 -> 转换成 plist 数据更加直观
//        //(array as NSArray).write(toFile: "/Users/chenmingguang/Desktop/demo.plist", atomically: true)
//        //数组 -> json 序列化
//         let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        //let filURL = NSURL.fileURL(withPath: "/Users/chenmingguang/Desktop/demo.json")
//
//        (data as NSData).write(toFile:"/Users/chenmingguang/Desktop/demo.json" ,atomically:true)

        //遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array {
            arrayM.append(controller(dict: dict))
        }
        //设置tabBar 的子控制器
        viewControllers=arrayM
    }
    
    //使用字典创建一个子控制器
    //parameter dict: 信息字典(clsName, title, imagName, visitorInfo)
    //returns：子控制器
    private func controller(dict: [String: AnyObject]) -> UIViewController{
        //1.取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imagName = dict["imagName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String: String]
            
            
            else{
                return UIViewController()
        }
        
        //创建视图控制器
        //2.将clsName 转换成 cls
        let vc=cls.init()


        //设置控制器的访客信息字典
        //vc.visitorInfoDictionary = visitorDict
        
        //3.设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imagName)
        vc.tabBarItem.selectedImage=UIImage(named: "tabbar_" + imagName + "_selected")?
            .withRenderingMode(.alwaysOriginal)
        
        // 4. 设置 tabbar 的标题字体（大小）
        vc.tabBarItem.setTitleTextAttributes(
            [NSAttributedString.Key.foregroundColor: UIColor.orange],
            for: .highlighted)
        // 系统默认是 12 号字，修改字体大小，要设置 Normal 的字体大小
        //swift4.0以上用NSAttributedString.Key.font:
        vc.tabBarItem.setTitleTextAttributes(
            [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)],
            for: UIControl.State(rawValue: 0))
        
        //实例化导航控制器的时候，会调用push方法将 rootVC 压栈
        vc.title=title
        if title == "首页" {
            let nav = UINavigationController(rootViewController: vc)
            return nav
        }
        let nav = MGNavigationController(rootViewController: vc)
        return nav
        
    }
}
